package com.example.qu_tao.View;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.qu_tao.R;
import com.example.qu_tao.database.DBHelper;
import com.example.qu_tao.database.GoodsDao;
import com.example.qu_tao.entity.Goods;
import com.example.qu_tao.entity.Photo;

import java.util.List;

public class GoodsDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvGoodsName, tvGoodsPrice, tvGoodsAddress, tvGoodsContent;
    private ImageView ivGoodsImage, ivCollect;
    private Button btnShop, btnCustomer, btnCall, btnAddCart, btnBuyNow;
    private Goods currentGoods;
    private boolean isCollected = false;
    private GoodsDao goodsDao;
    public static final String ACTION_ORDER_UPDATED = "com.example.qu_tao.ACTION_ORDER_UPDATED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        // 初始化数据库访问对象
        goodsDao = new GoodsDao(this);

        // 1. 初始化控件
        initViews();

        // 2. 获取商品ID并加载详情
        int goodsId = getIntent().getIntExtra("goodsId", 0);
        loadGoodsDetail(goodsId);

        // 3. 设置点击事件
        setClickListeners();
    }

    private void initViews() {
        tvGoodsName = findViewById(R.id.tv_goods_name);
        tvGoodsPrice = findViewById(R.id.tv_goods_price);
        tvGoodsAddress = findViewById(R.id.tv_goods_address);
        tvGoodsContent = findViewById(R.id.tv_goods_content);
        ivGoodsImage = findViewById(R.id.iv_goods_image);
        ivCollect = findViewById(R.id.iv_collect);
        btnShop = findViewById(R.id.btn_shop);
        btnCustomer = findViewById(R.id.btn_customer);
        btnCall = findViewById(R.id.btn_call);
        btnAddCart = findViewById(R.id.btn_add_cart);
        btnBuyNow = findViewById(R.id.btn_buy_now);
    }

    private void loadGoodsDetail(int goodsId) {
        new Thread(() -> {
            currentGoods = goodsDao.getGoodsById(goodsId);
            runOnUiThread(() -> {
                if (currentGoods != null) {
                    // 更新UI
                    tvGoodsName.setText(currentGoods.getGoods_name());
                    tvGoodsPrice.setText("¥" + currentGoods.getGoods_price());
                    tvGoodsAddress.setText("发货地：" + currentGoods.getGoodsAddress());
                    tvGoodsContent.setText(currentGoods.getGoods_content());

                    // 设置商品图片
                    if (currentGoods.getPhotoList() != null && !currentGoods.getPhotoList().isEmpty()) {
                        byte[] imageData = currentGoods.getPhotoList().get(0).getData();
                        if (imageData != null && imageData.length > 0) {
                            ivGoodsImage.setImageBitmap(
                                    android.graphics.BitmapFactory.decodeByteArray(imageData, 0, imageData.length));
                        }
                    }
                }
            });
        }).start();
    }

    private void setClickListeners() {
        btnShop.setOnClickListener(this);
        btnCustomer.setOnClickListener(this);
        btnCall.setOnClickListener(this);
        btnAddCart.setOnClickListener(this);
        btnBuyNow.setOnClickListener(this);
        ivCollect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_shop) {
            startActivity(new Intent(this, WodeDianpuActivity.class));
        } else if (id == R.id.btn_customer) {
            startActivity(new Intent(this, LiaoYiLiaoActivity.class));
        } else if (id == R.id.btn_call) {
            showCallDialog();
        }else if (id == R.id.btn_add_cart) {
            Toast.makeText(this, "已加入购物车", Toast.LENGTH_SHORT).show();
            // 将商品信息插入到购物车表中
            ContentValues values = new ContentValues();
            values.put("goods_id", currentGoods.getGoods_id());
            values.put("goods_name", currentGoods.getGoods_name());
            values.put("goods_price", currentGoods.getGoods_price());
            values.put("goods_address", currentGoods.getGoodsAddress());
            values.put("goods_content", currentGoods.getGoods_content());
            getContentResolver().insert(Uri.parse("content://com.example.qu_tao.provider/cart"), values);
        } else if (id == R.id.btn_buy_now) {
            Toast.makeText(this, "下单成功", Toast.LENGTH_SHORT).show();
            // 将商品信息插入到订单表中
            ContentValues values = new ContentValues();
            values.put("goods_id", currentGoods.getGoods_id());
            values.put("goods_name", currentGoods.getGoods_name());
            values.put("goods_price", currentGoods.getGoods_price());
            values.put("goods_address", currentGoods.getGoodsAddress());
            values.put("goods_content", currentGoods.getGoods_content());
            getContentResolver().insert(Uri.parse("content://com.example.qu_tao.provider/order1"), values);

            // 发送广播通知订单页面更新数据
            Intent intent = new Intent(ACTION_ORDER_UPDATED);
            sendBroadcast(intent);
        } else if (id == R.id.iv_collect) {
            isCollected = !isCollected;
            ivCollect.setImageResource(isCollected ?
                    R.drawable.ic_collected : R.drawable.ic_uncollected);
            Toast.makeText(this, isCollected ? "收藏成功" : "已取消收藏", Toast.LENGTH_SHORT).show();

            if (isCollected) {
                // 保存商品信息到收藏表
                ContentValues values = new ContentValues();
                values.put("goods_id", currentGoods.getGoods_id());
                values.put("goods_name", currentGoods.getGoods_name());
                values.put("goods_price", currentGoods.getGoods_price());
                values.put("goods_address", currentGoods.getGoodsAddress());
                values.put("goods_content", currentGoods.getGoods_content());

                getContentResolver().insert(Uri.parse("content://com.example.qu_tao.provider/collection"), values);
            } else {
                // 取消收藏时，从收藏表中删除该商品信息
                getContentResolver().delete(Uri.parse("content://com.example.qu_tao.provider/collection/" + currentGoods.getGoods_id()), null, null);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (goodsDao != null) {
            goodsDao.close();
        }
    }
    private void showCallDialog() {
        new AlertDialog.Builder(this)
                .setTitle("拨打电话")
                .setMessage("确定要拨打电话给商家吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 实际拨打电话的逻辑（需要权限处理）
                    Toast.makeText(this, "正在拨打电话...", Toast.LENGTH_SHORT).show();
                    // 这里可以添加实际的拨号代码：
                    // Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:17519246041"));
                    // startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
    }
}